layui.use(['form', 'admin', 'ax','laydate','upload','formSelects'], function () {
    var $ = layui.jquery;
    var $ax = layui.ax;
    var form = layui.form;
    var admin = layui.admin;
    var upload = layui.upload;
    var laydate = layui.laydate;

    var enumAjax = new $ax(Feng.ctxPath + "/enums/deviceCate");
    var enumRes = enumAjax.start();
    var projects = enumRes.data;
    var html = "";
    for(var key in projects){
        html += '<option value="'+key+'">'+projects[key]+'</option>'
    }
    $("#cateId").append(html);

    var formSelects = layui.formSelects;
    formSelects.config('selTag', {
        searchUrl: Feng.ctxPath + "/enums/userTags",
        keyName: 'name',
        keyVal: 'id',
    });

    form.render('select');
    //表单提交事件
    form.on('submit(btnSubmit)', function (data) {
        var ajax = new $ax(Feng.ctxPath + "/nanSellerDevice/addItem", function (data) {
            if(data.success){
                 Feng.success("操作成功！");
                        window.location.href = Feng.ctxPath + '/nanSellerDevice'
            }else{
                Feng.error("操作失败！" + data.message)
            }
        }, function (data) {
            Feng.error("操作失败！" + data.responseJSON.message)
        });
        if(data.field.code.length > 6 || data.field.code.length < 4){
            Feng.error("编码必须是4-6位数字")
            return false;
        }
        var map = {};
        var keyMap = {};
        $(".nan-item").each(function(){
            var $this = $(this);
            var key = $this.parent(".nan-content").prev().find("span").text();
            keyMap[key] = $this.parent(".nan-content").prev().find(".nan-title-t").val();
            if($this.hasClass("nan-sel")){
                if(!map[key]) map[key] = [];
                map[key].push({
                    id: $this.data("id"),
                    defaultImg: $this.data("img"),
                    defaultImgSel: $this.data("imgs"),
                    defaultName: $this.find(".nan-name").text(),
                    dName: $this.find(".nan-mode").text(),
                    beginCode: $this.data("bcode"),
                    endCode: $this.data("ecode"),
                    imgSel: '',
                    img: '',
                    name: '',
                    forbid: 0
                });
            }
        })
        var arr = [];
        for(var key in map){
            var obj = {defaultKey: key, data: map[key], key: keyMap[key]}
            arr.push(obj);
        }
        if(arr.length === 0){
            Feng.error("请至少添加一路玩法")
            return false;
        }
        data.field.selfScene = JSON.stringify(arr);
        ajax.set(data.field);
        ajax.start();

        return false;
    });
//普通图片上传
    upload.render({
        elem: '#img'
        ,url: Feng.ctxPath + '/system/upload'
        ,done: function(res){
            if(res.success){
                $('#imgImgPreview').attr('src', Feng.cdn + res.data.finalName);
                $("input[name=img]").val(res.data.finalName);
                Feng.success("操作成功！");
            }else{
                Feng.error("操作失败！" + data.message)
            }
        }
        ,error: function(){
            Feng.error("操作失败！");
        }
    });
    var sceneAjax = new $ax(Feng.ctxPath + "/nanScene/listStruct");
    var sceneRes = sceneAjax.start();
    var sceneMap = sceneRes.data;
    var sceneHtml = "";
    console.log(sceneMap);
    for(var key in sceneMap){
        console.log(key);
        sceneHtml += key === '附加'? '<div class="nan-title"><span>'+key+'</span></div>':
            '<div class="nan-title"><span>'+key+'</span><input type="text" class="nan-title-t" placeholder="自定义名称" /></div>';
        sceneHtml += key === '附加'? '<div class="nan-content nan-narrow">': '<div class="nan-content">';
        var sceneValue = sceneMap[key];
        sceneValue.forEach(scene => {
            sceneHtml += '<div class="nan-item nan-sel" data-img="'+scene.img+'"  data-imgs="'+scene.imgSel+'" ' +
                ' data-bcode="'+scene.orderCode+'" data-ecode="'+scene.closeCode+'" data-id="'+scene.id+'">' +
                '    <img src="'+Feng.cdn + scene.imgSel +'" alt=""/>' +
                '    <div class="nan-name">'+scene.nickName+'</div>' +
                '    <div class="nan-mode">'+scene.name+'</div>' +
                '    <div class="nan-cover">' +
                '        <span class="nan-bg"></span>' +
                '        <span class="nan-icon">✔</span>' +
                '    </div>' +
                '</div>';
        })
        sceneHtml += '</div>';
    }
    $("#scene").html(sceneHtml);

    $(".nan-item").click(function(){
        var $this = $(this);
        if($this.hasClass("nan-sel")){
            $this.removeClass("nan-sel")
            $this.find("img").attr("src", Feng.cdn + $this.data("img"))
        }else{
            $this.addClass("nan-sel")
            $this.find("img").attr("src", Feng.cdn + $this.data("imgs"))
        }
    })

    $("#sellerId").click(function(){
        admin.open({
            id: 'addForm',
            type: 2,
            title: "选择运营组",
            shade: 0,
            area: ['800px', '600px'],
            content: '/nanSeller/choose'
        });
    })


    window.choose = function(data, type){
        if(type === 'seller'){
            $("input[name=sellerId]").val(data.id);
            $("#sellerName").text(data.name);
        }

    }

    $('#cancel').click(function(){
        window.location.href = Feng.ctxPath + '/nanSellerDevice'
    });

});
